package cc.ug_project.rollcall.Bussness.DataProviders

import cc.ug_project.rollcall.Bussness.DataModel.User
import cc.ug_project.rollcall.Bussness.DataModel.findObjects
import cc.ug_project.rollcall.Bussness.DataModel.save
import cc.ug_project.rollcall.Bussness.DataModel.update
import cn.bmob.v3.BmobQuery
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.FindListener

/**
 * Created by yeganaaa on 4/3/18.
 */
class UserDataProvider {
    fun SignIn(signInName: String, pwd: String, action: (user: User?, exception: BmobException?) -> Unit) {

        val query = BmobQuery<User>().apply {
            addWhereEqualTo("SignInName", signInName)
            addWhereEqualTo("Pwd", pwd)
            setLimit(1)
        }


        query.findObjects(object : FindListener<User>() {
            override fun done(objects: List<User>, exception: BmobException?) {
                if (exception == null) {
                    if (objects.size > 0)
                        action(objects[0], exception)
                    else
                        action(null, exception)
                } else action(null, exception)
                exception?.printStackTrace()
            }
        })
    }

    fun addUser(user: User, action: (objectId: String, exception: BmobException?) -> Unit) {
        user.save { objectId, exception ->
            action(objectId, exception)
        }
    }

    fun updateUser(user: User, action: (exception: BmobException?) -> Unit) {
        user.update {
            action(it)
            it?.printStackTrace()
        }
    }

    fun getAllUser(action: (objects: List<User>?, exception: BmobException?) -> Unit) {
        val query = BmobQuery<User>()


        query.findObjects(object : FindListener<User>() {
            override fun done(objects: List<User>, exception: BmobException?) {
                if (exception == null) {
                    if (objects.size > 0)
                        action(objects, exception)
                } else action(null, exception)
                exception?.printStackTrace()
            }
        })
    }
}